<template>
	<view class="container">
		<u-modal :show="show"
			:title="title + '密码'"
			:confirmText="title"
			cancelText="取消"
			showCancelButton
			buttonReverse
			closeOnClickOverlay
			@confirm="confirm"
			@cancel="show = false">
			<u--form
				labelPosition="left"
				:model="password"
				:rules="rules"
				ref="form">
				<u-form-item
					label="名称"
					prop="passwordName"
					borderBottom>
					<u--input v-model="password.passwordName" border="none"/>
				</u-form-item>
				<u-form-item
					label="账号"
					prop="account"
					borderBottom>
					<u--input v-model="password.account" border="none"/>
				</u-form-item>
				<u-form-item
					label="密码"
					prop="password"
					borderBottom>
					<u--input v-model="password.password" border="none"/>
				</u-form-item>
				<u-form-item
					label="备注"
					prop="remark"
					borderBottom>
					<u--input v-model="password.remark" border="none"/>
				</u-form-item>
			</u--form>
		</u-modal>
	</view>
</template>

<script>
export default {
	components: {},

	data() {
		return {
			show: false,
			// 密码
			password: {
				account: null,
				password: null,
				remark: null
			},
			rules: {
				passwordName: {
					required: true,
					message: '请输入名称'
				},
				account: {
					required: true,
					message: '请输入账号'
				},
				password: {
					required: true,
					message: '请输入密码'
				}
			}
		};
	},
	computed: {
		title() {
			return this.password.passwordId ? '修改' : '添加';
		}
	},
	methods: {
		/**
		 * 初始化
		 *
		 * @param password 密码
		 */
		init(password) {
			this.$nextTick(() => {
				if (this.$refs.form) {
					// 初始化添加或修改控件
					this.$refs.form.clearValidate();
				}
			});
			this.password = JSON.parse(JSON.stringify(password));
			this.show = true;
		},

		/**
		 * 确定按钮
		 */
		async confirm() {
			// 表单校验
			await this.$refs.form.validate();
			// 进行添加
			if (this.title === '添加') {
				this.passwordService.add(this.password);
			} else {
				this.passwordService.update(this.password);
			}
			// 清除表单
			this.show = false;
			uni.$emit('success', this.title + '成功');
			this.$emit('finish');
			this.password = {};
		}
	}
}
</script>

<style scoped>
.container {
	padding: 0 10px;
}
</style>
